package com.gulimall.cart.Interceptor;

import com.common.constant.CartConstant;
import com.common.constant.LoginConstant;
import com.common.to.MemberTo;
import com.gulimall.cart.to.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author Rookie-6688
 * @Description 购物车拦截方法，用于在查看购物车之前匹配对应的 user-key Cookie，从而返回匹配的购物车数据
 * @Create 2021-04-25 16:18
 */
public class CartInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 执行前拦截，将请求携带的cookie存入 threadLocal
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberTo memberTo = (MemberTo) request.getSession().getAttribute(LoginConstant.LOGIN_USERNAME);
        UserInfoTo userInfoTo = new UserInfoTo();
        // 如果已登录将ID加入属性
        if(memberTo != null){
            userInfoTo.setUserId(memberTo.getId());
        }

        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length>0)
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(CartConstant.CART_COOKIE_NAME)){
                userInfoTo.setUserKey(cookie.getValue());
                userInfoTo.setTempUser(true);
            }
        }

        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            // 如果为空，说明没有传来对应的 Cookie，那么就创建一个UUID的Cookie
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }
        threadLocal.set(userInfoTo);
        return true;
    }


    /**
     * 返回请求前执行，将对应的user_key 的Cookie返回回去
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();

        boolean isEmpty = true;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(CartConstant.CART_COOKIE_NAME)){
                isEmpty = false;
            }
        }

        // 如果不是临时用户或是第一次绑定的临时用户，那么就返回user_key 的Cookie
        if(!userInfoTo.getTempUser() || isEmpty){
            Cookie cookie = new Cookie(CartConstant.CART_COOKIE_NAME,userInfoTo.getUserKey());
            // 如果不是临时用户，那么就延长有效时间
            cookie.setDomain("cart.gulimall.com");
            cookie.setMaxAge(CartConstant.CART_COOKIE_LIVE_TIME);
            response.addCookie(cookie);
        }
    }

}
